package com._21cn.cms.article.utils;

import com._21cn.cms.article.Constants;
import com._21cn.cms.article.entity.Article;
import com._21cn.cms.article.entity.ColumnArticle;
import com._21cn.cms.article.entity.RegionArticle;
import com._21cn.cms.article.entity.vo.ArticlePushResult;
import com._21cn.cms.article.service.ColumnArticleService;
import com._21cn.cms.article.service.RegionArticleService;
import com._21cn.cms.site.entity.Column;
import com._21cn.cms.site.entity.Region;
import com._21cn.cms.site.service.ColumnService;
import com._21cn.cms.site.service.RegionService;
import com._21cn.framework.utils.DateUtil;
import com._21cn.framework.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by Thinkpad on 2017/4/7.
 */
@Component
public class ArticlePushHelper {

    @Autowired(required = false)
    private ColumnService columnService;

    @Autowired(required = false)
    private RegionService regionService;

    @Autowired(required = false)
    private ColumnArticleService columnArticleService;

    @Autowired(required = false)
    private RegionArticleService regionArticleService;

    @Autowired(required = false)
    private ArticleHelper articleHelper;

    @Autowired(required = false)
    private PublishHelper publishHelper;

    /**
     * 插入主栏目文章
     * @param article
     * @param columnId
     * @param generatePage
     */
    public ArticlePushResult insertMainColumnArticle(Article article, Integer columnId, boolean generatePage ){
        ArticlePushResult result = getPushColumnArticleResult(article, columnId, false);
        if( result.getStatus() == Constants.PUSH_STATUS_SUCCESS ){
            Column column = result.getColumn();
            articleHelper.softCopyArticle(column, article, Constants.PUBLISH_COLUMN_MASTER);    //软复制
            if( generatePage ){
                publishHelper.publishArticle(article);
                publishHelper.addColumnTask(columnId);
                publishHelper.addChannelTask(column.getChannelId());
            }
        }
        return result;
    }

    /**
     * 插入从栏目文章
     * @param article
     * @param columnIds
     * @param generatePage
     */
    public List<ArticlePushResult> insertRelateColumnArticle(Article article, String columnIds, boolean generatePage ){
        Set<Integer> columnIdSet = StringUtil.str2IntSet(columnIds);
        List<ArticlePushResult> resultList = new ArrayList<ArticlePushResult>();
        for( Integer columnId : columnIdSet ){
            ArticlePushResult result = getPushColumnArticleResult(article, columnId, false);
            if( result.getStatus() == Constants.PUSH_STATUS_SUCCESS ){
                Column column = result.getColumn();
                articleHelper.softCopyArticle(column, article, Constants.PUBLISH_COLUMN_SLAVE); //软复制至从栏目
                if (!article.getChannelId().equals(column.getChannelId())) {
                    article.setColumn(column);
                    article.setChannel(column.getChannel());
                    article.setSite(column.getSite());
                    article.setArticleUrl(article.regulateArticleUrl());
                    this.publishHelper.generateArticleJsonFile(article);
                }
                if( generatePage ){
                    publishHelper.addColumnTask(columnId);
                }
            }
            resultList.add(result);
        }
        return resultList;
    }

    /**
     * 插入区块文章
     * @param article
     * @param regionIds
     * @param generatePage
     */
    public List<ArticlePushResult> insertRegionArticles( Article article, String regionIds, boolean generatePage ){
        Set<Integer> regionIdSet = StringUtil.str2IntSet(regionIds);
        List<ArticlePushResult> resultList = new ArrayList<ArticlePushResult>();
        for( Integer regionId : regionIdSet ){
            ArticlePushResult result = getPushRegionArticleResult( article, regionId );
            if( result.getStatus() == Constants.PUSH_STATUS_SUCCESS ){
                RegionArticle regionArticle = new RegionArticle();
                regionArticle.initWith( article );
                regionArticle.setRegionId(regionId);
                regionArticleService.insert(regionArticle);
                if( generatePage ){
                    publishHelper.addRegionTask(regionId);  //TODO 更新页面（频道、栏目、最终页）
                }
            }else if (result.getStatus() == Constants.PUSH_STATUS_AGAIN) {
                RegionArticle regionArticle = this.regionArticleService.getRegionArticle(regionId, article.getId());
                regionArticle.initWith(article);
                regionArticle.setRegionId(regionId);
                this.regionArticleService.update(regionArticle);
                if (generatePage) {
                    this.publishHelper.addRegionTask(regionId.intValue());
                }
            }
            resultList.add(result);
        }
        return resultList;
    }

    /**
     * 更新主栏目文章
     * @param article
     * @param columnId
     * @param generatePage
     */
    public ArticlePushResult updateMainColumnArticle(Article article, Integer columnId, boolean generatePage ){
        ArticlePushResult result = getPushColumnArticleResult(article, columnId, true);
        if( result.getStatus() == Constants.PUSH_STATUS_SUCCESS ){
            Column column = result.getColumn();
            ColumnArticle columnArticle = columnArticleService.getMasterArticle(article.getId());
            if( columnArticle==null ){
                columnArticle = new ColumnArticle();
                columnArticle.initColumnArticle(column, article);
                columnArticleService.insert(columnArticle);
            }else {
                columnArticle.initColumnArticle(column, article);
                columnArticleService.update(columnArticle);
            }
            if( generatePage ){
                publishHelper.publishArticle(article);
                publishHelper.addColumnTask(columnId);  //TODO 更新页面（频道、栏目、最终页）
                publishHelper.addRelateTask(columnId.intValue());
                publishHelper.addChannelTask(column.getChannelId().intValue());
            }
        }
        return result;
    }

    public void updateRelateColumnArticle(Article article, String columnIds, boolean generatePage ){
        if(StringUtil.isEmpty(columnIds)){      //如果没有从栏目，则删除旧的
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("eqArticleId", article.getId());
            params.put("eqSlaveFlag", Constants.PUBLISH_COLUMN_SLAVE);
            columnArticleService.delete(params);
        }else {
            List<Integer> deleteList = new ArrayList<Integer>();
            List<Integer> updateList = new ArrayList<Integer>();
            Set<Integer> columnIdSet = StringUtil.str2IntSet(columnIds);
            String oldRelateColumnIds = article.getRelateColumnIds();
            Set<Integer> oldRelateColumnIdSet = StringUtil.str2IntSet(oldRelateColumnIds);
            for(Integer oldColumnId : oldRelateColumnIdSet){
                if(!columnIdSet.contains(oldColumnId)){
                    deleteList.add(oldColumnId);
                }else {
                    updateList.add(oldColumnId);
                }
            }
            if(!deleteList.isEmpty()){      //如果旧的不在新的列表中，删除
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("inColumnIdList", deleteList);
                params.put("eqArticleId", article.getId());
                params.put("eqSlaveFlag", Constants.PUBLISH_COLUMN_SLAVE);
                columnArticleService.delete(params);
            }
            if (!updateList.isEmpty()) {
                Object params = new HashMap();
                ((Map)params).put("inColumnIdList", updateList);
                ((Map)params).put("eqArticleId", article.getId());
                ((Map)params).put("eqSlaveFlag", Integer.valueOf(1));
                List<ColumnArticle> list = this.columnArticleService.getList((Map)params, 1, 10, false);
                for (ColumnArticle columnArticle : list) {
                    Column column = this.columnService.getById(columnArticle.getColumnId());
                    columnArticle.initColumnArticle(column, article);
                    this.columnArticleService.update(columnArticle);
                }
            }
            insertRelateColumnArticle(article, columnIds, generatePage);    //插入（包括去重）
        }
    }

    /**
     * 插入区块文章
     * @param article
     * @param regionIds
     * @param generatePage
     */
    public void updateRegionArticles( Article article, String regionIds, boolean generatePage ){
        if(StringUtil.isEmpty(regionIds)){      //如果没有区块，则删除旧的
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("eqArticleId", article.getId());
            regionArticleService.delete(params);
        }else {
            List<Integer> deleteList = new ArrayList<Integer>();
            Set<Integer> regionIdSet = StringUtil.str2IntSet(regionIds);
            String oldRegionIds = article.getRegionIds();
            Set<Integer> oldRegionIdSet = StringUtil.str2IntSet(oldRegionIds);
            for(Integer oldRegionId : oldRegionIdSet){
                if(!regionIdSet.contains(oldRegionId)){
                    deleteList.add(oldRegionId);
                }
            }
            if(!deleteList.isEmpty()){      //如果旧的不在新的列表中，删除
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("inRegionIdList", deleteList);
                params.put("eqArticleId", article.getId());
                regionArticleService.delete(params);
            }
            insertRegionArticles(article, regionIds, generatePage);    //插入（包括去重）
        }
    }


    private ArticlePushResult getPushRegionArticleResult( Article article, int regionId ){
        ArticlePushResult articlePushResult = new ArticlePushResult();
        if( article==null || article.getId()<=0 || article.getColumnId()<=0 ||
                article.getPublishStatus()==Constants.PUBLISH_STATUS_NONE ||
                article.getPublishStatus()==Constants.PUBLISH_STATUS_CANCEL ){
            articlePushResult.setStatus(Constants.PUSH_STATUS_FAIL);
            articlePushResult.setResultMsg("推送到区块"+regionId+" 不成功，原因：文章状态异常");
            return articlePushResult;
        }
        Region region = regionService.getById(regionId);
        if( region==null || region.getStatus()== com._21cn.cms.common.Constants.STATUS_CLOSE ){
            articlePushResult.setStatus(Constants.PUSH_STATUS_FAIL);
            articlePushResult.setResultMsg("推送到区块"+regionId+" 不成功，原因：区块状态异常");
            return articlePushResult;
        }
        RegionArticle regionArticle = regionArticleService.getRegionArticle(regionId, article.getId());
        if(regionArticle!=null ){
            articlePushResult.setStatus(Constants.PUSH_STATUS_AGAIN);
            articlePushResult.setResultMsg("推送到区块"+regionId+" 不成功，原因：重复推送");
            return articlePushResult;
        }
        articlePushResult.setStatus(Constants.PUSH_STATUS_SUCCESS);
        articlePushResult.setResultMsg("推送到区块"+regionId+" 成功");
        articlePushResult.setRegion(region);
        articlePushResult.setArticle(article);
        return articlePushResult;
    }

    /**
     * 预先获取推送结果
     * @param article
     * @param columnId
     * @return
     */
    private ArticlePushResult getPushColumnArticleResult( Article article, int columnId, boolean allowDuplicate ){
        ArticlePushResult articlePushResult = new ArticlePushResult();
        if( article==null || article.getId()<=0 || article.getColumnId()<=0 ||
                article.getPublishStatus()==Constants.PUBLISH_STATUS_NONE ||
                article.getPublishStatus()==Constants.PUBLISH_STATUS_CANCEL ){
            articlePushResult.setStatus(Constants.PUSH_STATUS_FAIL);
            articlePushResult.setResultMsg("推送到栏目"+columnId+" 不成功，原因：文章状态异常");
            return articlePushResult;
        }
        Column column = columnService.getById(columnId);
        if( column==null || column.getStatus()== com._21cn.cms.common.Constants.STATUS_CLOSE
                || column.getChannel().getId()<=0 || column.getChannel().getStatus() == com._21cn.cms.common.Constants.STATUS_CLOSE){
            articlePushResult.setStatus(Constants.PUSH_STATUS_FAIL);
            articlePushResult.setResultMsg("推送到 "+columnId+" 不成功，原因：栏目状态异常");
            return articlePushResult;
        }
        if( !allowDuplicate ){
            ColumnArticle columnArticle = columnArticleService.getColumnArticle(columnId, article.getId());
            if(columnArticle!=null ){
                articlePushResult.setStatus(Constants.PUSH_STATUS_AGAIN);
                articlePushResult.setResultMsg("推送到 "+columnId+" 不成功，原因：重复推送");
                return articlePushResult;
            }
        }
        articlePushResult.setStatus(Constants.PUSH_STATUS_SUCCESS);
        articlePushResult.setResultMsg("推送到 "+columnId+" 成功");
        articlePushResult.setColumn(column);
        articlePushResult.setArticle(article);
        return articlePushResult;
    }

}
